package com.gzhryc.shared_device.oem.micro.queue.work;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.bxscn.code.dao.db.BXSCNOrder;
import com.gzhryc.shared_device.bxscn.code.services.BXSCNOrderService;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;

import java.util.Date;
import java.util.List;

public class BXSCNCacheFinishCheckRunnable implements Runnable{

    static Logger log = Logger.getLogger(BXSCNCacheFinishCheckRunnable.class);

    OperateInfo operateInfo;

    public BXSCNCacheFinishCheckRunnable(OperateInfo operateInfo){
        this.operateInfo = operateInfo;
    }

    @Override
    public void run() {
        try {
            List<BXSCNOrder> deviceOrderList = RedisCacheManager.findWorkingBXSCNDeviceOrder();
            if (deviceOrderList != null && deviceOrderList.size() > 0) {
                for (BXSCNOrder deviceOrder : deviceOrderList) {
                    if(StringTools.isBlank(deviceOrder.getTradeNo())){
                    	RedisCacheManager.removeWorkingBXSCNDeviceOrder("null");
                        log.error("便携式储能缓存订单，无订单号，数据：{{0:json}}",deviceOrder);
                        continue;
                    }
                    //从数据库获取设备订单信息，避免缓存脏数据
                    deviceOrder = BXSCNOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                    //TODO 检查订单状态

                    Date startDate = deviceOrder.getStartDate();
                    if (startDate == null) {
                        startDate = deviceOrder.getCreateDate();
                    }
                    Long hour = DateTools.differenceHour(startDate, new Date());

                    Integer day = hour.intValue() / 24;
                    Integer surplusHour = hour.intValue() % 24;

                    Integer payMoney = day * deviceOrder.getDayMaxMoney();
                    payMoney = payMoney + (deviceOrder.getPayIntervalMoney() * surplusHour);

                    if (payMoney >= deviceOrder.getDepositMoney()) {
                        operateInfo.setOperateNote("共享充电宝租借已到押金金额，已未归还方式结束");

                        try {
                            //清理缓存，避免定时器重复处理
                            RedisCacheManager.removeWorkingCDCZDeviceOrder(deviceOrder.getTradeNo());

                            int result = BXSCNOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder, payMoney, PayServiceFactory.self(), operateInfo);
                            if (result == 2) {
                                //订单已经完成，同步会员订单
                                deviceOrder = BXSCNOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                                if (MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(), deviceOrder.getMoney(), deviceOrder.getPayMoney()
                                        , deviceOrder.getWalletMoney(),operateInfo)) {
                                    log.error("共享充电宝订单完成，但同步会员订单失败，订单号：{{0}}", deviceOrder.getTradeNo());
                                }

                                JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                                if (producer != null) {
                                    OrderFinishEvent event = new OrderFinishEvent(EBusinessType.BXSCN.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(), operateInfo);
                                    KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                    producer.send(kafkaMessage);
                                }else{
                                    log.error("未初始化消息队列，订单{{0}}未触发完成事件",deviceOrder.getTradeNo());
                                }
                            }
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }
}
